%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                         %
%                              Calibration                                %
%                                                                         %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


% ---------------------------- Description -------------------------------- 

    % This script calibrates the model to match its moments to the data.
    % Basically, it forms a system of equations that ensure the equality of
    % the moments and uses a minimization algorithm to find its solution.

%--------------------------------------------------------------------------
%                              Calibration                                %
%--------------------------------------------------------------------------

fprintf('------------------------- Calibration stage started --------------------------\n')

    % If the calibration switch is turned off...
    if Compute_Calibration == 0

         % ... the code loads the parameters already saved...
        load paramguess

    % ... else we use an algorithm to calibrate the model
    else


        % ... loads current parameter vector for initial guess
        load paramguess

        % ... turns Calibration_Function as function of parameters only
        fun = @(x) Calibration_Function(x, p);

        % ... adds a tracker to the process
        options = optimset('PlotFcns',@optimplotfval);

        % ... solves the calibration routine using fminsearchbnd (bounds defined inside the square brackets)
        [paramguess, val] = fminsearchbnd(fun, paramguess, [0, 1, 0, 0, 0], [Inf, 1.125, Inf, 0.35, Inf], options);

        % ... saves results to the paramguess vector
        %save paramguess paramguess

    end

fprintf('-------------------------- Calibration stage ended ---------------------------\n')
fprintf('\n\n')